const {
    success,
    fail
} = require('../utils/R')
const jwt = require('jsonwebtoken');
const accountServices = require('../service/accountServices')
const {jwt_secret} = require('../utils/config')
function accountController() {
    return {
        //登录
        async login(ctx, next) {
            const requestBody = ctx.request.body;
            if (!requestBody.name || !requestBody.password) {
                ctx.body = fail('用户名或密参数不合法码错误')
            }
            try {
                const data = await accountServices.login(requestBody)                
                if (data.length) {
                    let tokenData = data.pop()
                    const token = jwt.sign({
                            account: tokenData.account,
                            id: tokenData._id
                        },
                        jwt_secret, // secret
                        {
                            expiresIn: '1h'
                        }
                    );

                    ctx.body = success(token, '登录成功')

                } else {
                    ctx.body = fail('用户名或密码错误')
                }
            } catch (error) {
                ctx.body = fail(error)
            }
            next()
        },
        //注册
        async register(ctx, next) {
            const requestBody = ctx.request.body
            try {
                const data = await accountServices.register(requestBody)
                ctx.body = success(data, '保存成功')
            } catch (error) {
                console.log('error', error)
                ctx.body = fail(error)
            }
            next()
        }

    }
}

module.exports = accountController()